package com.sunrise.gateway.web.servlet;

import com.sunrise.gateway.commons.CommonUtils;
import com.sunrise.gateway.commons.Result;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class FrontendErrorLogServlet extends ServletBase {
    private final static Logger errorLog = LoggerFactory.getLogger("error");

    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doMyPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String log = CommonUtils.inputStream2String(req.getInputStream());
        handleLog(log, resp);
    }
    @Override
    protected void doMyGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String log = req.getParameter("log");
        handleLog(log, resp);
    }

    private static void handleLog(String log, HttpServletResponse resp) throws ServletException, IOException {
        if (!StringUtils.isEmpty(log)) {
            errorLog.error("{}", log);
        }

        Result result = new Result(com.dap.commons.Constants.ResponseCode.SYS_SUCCESS, "ok", null);
        CommonUtils.writeStrIntoResponse(result.toJsonString(), resp);
    }

}
